﻿using Microsoft.Extensions.Configuration;
using Simple.Common.Dtos.Dtos;
using System;
using System.IO;
using Common.Core.Exceptions;

namespace Simple.Common.Core.Config
{
    /// <summary>
    /// 配置文件帮助类
    /// </summary>
    public class ConfigurationHelper
    {
        private static IConfigurationRoot _CurrentConfiguration;

        /// <summary>
        /// 当前配置
        /// </summary>
        public static IConfigurationRoot CurrentConfiguration
        {
            get
            {
                if (_CurrentConfiguration != null) return _CurrentConfiguration;
                var builder = new ConfigurationBuilder()
                    .SetBasePath(Path.GetDirectoryName(typeof(ConfigurationHelper).Assembly.Location))
#if DEBUG
                    .AddJsonFile("appsettings.Development.json", optional: true);
#else
                        .AddJsonFile("appsettings.json", optional: true);
#endif
                _CurrentConfiguration = builder.Build();
                //使用公共的全局配置
                var configPath = _CurrentConfiguration.GetValue("CommConfigPath", "");
                if (string.IsNullOrEmpty(configPath)) return _CurrentConfiguration;
                var builderAll = new ConfigurationBuilder()
                    .SetBasePath(configPath)
#if DEBUG
                    .AddJsonFile("appsettings.Development.json", optional: true);
#else
                        .AddJsonFile("appsettings.json", optional: true);
#endif
                _CurrentConfiguration = builderAll.Build();
                return _CurrentConfiguration;
            }
        }

        /// <summary>
        /// 获取运行根路径
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            return Path.GetDirectoryName(typeof(ConfigurationHelper).Assembly.Location);
        }
        /// <summary>
        /// 获取配置项
        /// </summary>
        /// <param name="key">Key，如："ConnectionString:AdminDB"</param>
        /// <returns></returns>
        public static string GetValue(string key)
        {
            var configuration = CurrentConfiguration;
            return configuration.GetSection(key).Value;
        }
        /// <summary>
        /// 获取配置项
        /// </summary>
        /// <param name="key">如：AuthServer:AuthScope</param>
        /// <returns></returns>
        public static T GetValue<T>(string key)
        {
            try
            {
                var configuration = CurrentConfiguration;
                return configuration.GetValue<T>(key);
            }
            catch (Exception e)
            {
                throw new BusinessException("获取配置文件失败",e);
            }
        }
        public static HysServerOptions ServerOptions
        {
            get
            {
                var configuration = CurrentConfiguration;
                return configuration.Get<HysServerOptions>(); ;
            }

        }
    }
}
